/**
 * Created by Administrator on 2017/3/28 0028.
 */
import  React from 'react'
import '../App.css'
import DisplayLog from './DisplayLog'
import Button from './Button'
import formatTime from '../util/formatTime'

class TimeDisplay extends React.Component {
    //构造函数中对状态初始值
    constructor(props) {
        super(props);
        this.state = {
            time: 0,
            on: false,
            logs: new Array()
        }
    }


    handleToggle() {
        // setInterval(function () {
        //     this.setState({time:this.state.time+1});
        // },10);
        // console.log("handleToggle");
        if (this.state.on) {
            clearInterval(this.timer);
        } else {
            this.timer = setInterval(()=> {
                this.setState({time: this.state.time + 1})
                console.log("timer " + this.state.time);
            }, 10);
        }
        this.setState({on: !this.state.on});
        //function  bindthis  改变 this 指针
        // setInterval(function () {
        //     this.setState({time:this.state.time+1})
        //     console.log("timer "+ this.state.time);
        // }.bind(this),10)
    }

    saveLog= ()=>{
        this.state.logs.push(this.state.time);
        console.log(this.state.logs)
    }

    clearLog=()=>{
        this.setState({logs:[]});
    }

    resetLog = ()=>{
        this.setState({time:0});

    }
    render(){
        var timeStr = formatTime(this.state.time);
        return <div>
            <h1 className="display-time">{timeStr}</h1>
            <div >
                <Button className={this.state.on ? "danger" : "success"} text={this.state.on ? "暂停":"开始"}
                        onClick={this.handleToggle.bind(this)}></Button>
                <Button className="warning" text="重置" onClick={this.resetLog} ></Button>
                <Button className="primary" text="记录" onClick={this.saveLog} ></Button>
                <Button className="undefined"  onClick={this.clearLog}></Button>
            </div>
            <DisplayLog log={this.state.logs}></DisplayLog>
        </div>
    }

    componentDidMount(){
        window.addEventListener('keydown',e=>{
            e.preventDefault();
        });
        window.addEventListener('keyup',e=>{
            e.preventDefault();
            // alert("up")
        });
    }
}
//
// class A {
//
// }
export default TimeDisplay;
// export default TimeDisplay as A;

// export {TimeDisplay,A}